/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package sistema.clinica.riobamba.desktop;

import Clases.SignosVitales;
import Funciones.FuncionesSignosVitales;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Enumeration;
import java.util.ResourceBundle;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.util.Duration;

/**
 * FXML Controller class
 *
 * @author xavier
 */
public class ServicioOnlineController implements Initializable, SerialPortEventListener {

    @FXML
    Label lblUser;
    @FXML
    Button btnCerrarSesion;
    @FXML
    Label lblOxigeno;
    @FXML
    Label lblPulso;
    @FXML
    LineChart lc;
    @FXML
    NumberAxis xAxis;
    @FXML
    ComboBox comboBox;

    //private XYChart.Series<Number, Number> hourDataSeries;
    private XYChart.Series<Number, Number> series = new XYChart.Series<Number, Number>();

    private Timeline animation;

    private double hours = 0;
    private double minutes = 0;
    private double timeInHours = 0;

    boolean flag;

    private SistemaClinicaRiobambaDesktop application;

    public void setApp(SistemaClinicaRiobambaDesktop application) {
        this.application = application;
//           if (application.getLoggedUser() != null) {
//                lblUser.setText(application.getLoggedUser().getNombres() + " " + application.getLoggedUser().getApellidos());
//                sv.setId_paciente(application.getLoggedUser().getId_p());
//            }
    }

    FileWriter fichero = null;
    PrintWriter pw = null;

    @Override
    public void initialize(URL url, ResourceBundle rb) {

        sv = new SignosVitales();                
        flag = false;
        series = new XYChart.Series<Number, Number>();

        ObservableList listaPuertos = null;
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
        while (portEnum.hasMoreElements()) {
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            if (listaPuertos == null) {
                listaPuertos = FXCollections.observableArrayList(currPortId.getName());
            } else {
                listaPuertos.add(currPortId.getName());
            }
        }
        comboBox.setItems(listaPuertos);
                
//        try {
//            fichero = new FileWriter("C:\\Users\\xavier\\Desktop\\pruebaXavi.txt");
//            pw = new PrintWriter(fichero);
//        } catch (Exception e) {
//        } finally {
//            try {
//                // Nuevamente aprovechamos el finally para 
//                // asegurarnos que se cierra el fichero.
//                if (null != fichero) {
//                    //fichero.close();
//                }
//            } catch (Exception e2) {
//                e2.printStackTrace();
//            }
//        }        
        
//        try {
//            BufferedReader input = new BufferedReader(new FileReader("C:\\Users\\xavier\\Desktop\\pruebaXavi.txt"));
//            String line = null;
//            while ((line = input.readLine()) != null) {
//                String[] datos = line.split(";");
//                if (datos.length == 4) {
//                    if (Double.parseDouble(datos[0]) <= 69000) {
//                        series.getData().add(new XYChart.Data<Number, Number>(Double.parseDouble(datos[0]), Double.parseDouble(datos[1])));
//                        //System.out.println("cargando valores");
//                    }
//                }
//            }
//            input.close();
//        } catch (Exception ex) {
//
//        }
        lc.getData().add(series);

        //lc.getData().add(hourDataSeries);
        // TODO                              
        animation = new Timeline();
        //Cambiar aqui el numero para la velocidad en que se muestran los datos. (100)
        animation.getKeyFrames().add(new KeyFrame(Duration.millis(40), new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                // 6 minutes data per frame
                for (int count = 0; count < 6; count++) {
                    nextTime();
                    plotTime();
                }
            }
        }));
        animation.setCycleCount(Animation.INDEFINITE);
        play();                
    }

    private void nextTime() {
        if (minutes == 59) {
            hours++;
            minutes = 0;
        } else {
            minutes++;
        }
        timeInHours = hours + ((1d / 60d) * minutes);
//        if (minutes == 960) {
//            hours++;
//            minutes = 0;
//        } else {
//            minutes += 40;
//        }
//        timeInHours = hours + ((1d / 1000d) * minutes);
    }

    private void plotTime() {
//        xAxis.setLowerBound(xAxis.getLowerBound() + 40);
//        xAxis.setUpperBound(xAxis.getUpperBound() + 40);

//        if (false) {
        if ((timeInHours % 1) == 0) {
            /*
             //y = (Math.random() * 5); //= prevY - 10;// + (Math.random()*20);            
             lblOxigeno.setText(String.valueOf(oxi));
             lblPulso.setText(String.valueOf(pul));
             hourDataSeries.getData().add(new XYChart.Data<Number, Number>(timeInHours, y));
             */
            //series.getData().add(new XYChart.Data<Number, Number>(timeInHours, y));
            //series.getData().add(new XYChart.Data<Number, Number>(x, y));
            //if (timeInHours > 5001 ) {
//            if (x > 5000) {
//                series.getData().remove(0);
//                //hourDataSeries.getData().remove(0);
//            }
            //if (timeInHours > 5000 ) {
            //if (x > 5000) {
            xAxis.setLowerBound(xAxis.getLowerBound() + 250);
            xAxis.setUpperBound(xAxis.getUpperBound() + 250);
            //}

        }
    }

    public void play() {
        animation.play();
    }

    public void processLogout(ActionEvent event) {
        if (application == null) {            
            return;
        }
        application.userLogout();
    }

    //LO DE ARDUINO
    BufferedReader input = null;
    SerialPort serialPort;
    private String PORT_NAME;// = "COM5";
    private static final int TIME_OUT = 10000;
    private static final int DATA_RATE = 9600;

    double tiempo;
    double hcg;
    int pr;
    int sp;

    SignosVitales sv;
    
    public void setInput(BufferedReader input) {
        this.input = input;
    }

    public SerialPort getSerialPort() {
        return serialPort;
    }

    public SignosVitales getSv() {
        return sv;
    }    

    public void ArduinoConnection() {

        PORT_NAME = comboBox.getValue().toString();
        CommPortIdentifier portId = null;
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
        while (portId == null && portEnum.hasMoreElements()) {
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            if (PORT_NAME.equals(currPortId.getName())) {
                portId = currPortId;
                break;
            }
        }
        if (portId == null) {
            return;
        }
        try {
            serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT);
            serialPort.setSerialPortParams(DATA_RATE,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);
            serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);
            if (serialPort != null) {
                animation.play();
            }

        } catch (Exception e) {
        }
    }

    @Override
    public void serialEvent(SerialPortEvent spe) {
        try {
            switch (spe.getEventType()) {
                case SerialPortEvent.DATA_AVAILABLE:
                    if (input == null) {

                        input = new BufferedReader(
                                new InputStreamReader(
                                        serialPort.getInputStream()));
                    }
                    //pw.println(input.readLine());
                    String inputLine = input.readLine();
                    pw.println(inputLine);
                    String[] datos = inputLine.split(";");
                    //System.err.println(datos[0]+" "+datos[1]);                    
                    if (datos.length == 4) {
                        if (Double.parseDouble(datos[0]) >= 0 && Double.parseDouble(datos[0]) <= 3 && !flag) {
                            flag = true;
                        }
                        if (flag) {
                            tiempo = Double.parseDouble(datos[0]);
                            hcg = Double.parseDouble(datos[1]);
                            pr = Integer.parseInt(datos[2]);
                            sp = Integer.parseInt(datos[3]);                            
                            lblOxigeno.setText(datos[3]);
                            lblPulso.setText(datos[2]);
                            sv.setTiempo(tiempo);
                            sv.setHcg(hcg);
                            sv.setPr(pr);
                            sv.setPs(sp);
                            series.getData().add(new XYChart.Data<Number, Number>(tiempo, hcg));
                            
                            //FuncionesSignosVitales.insertar(sv);                                                        
                        }
                    }

                    break;

                default:
                    break;
            }
        } catch (Exception e) {
            System.err.println(e.toString() + "    " + e.getStackTrace());
        }
    }

    public void actualizaPuertos() {
        ObservableList listaPuertos = null;
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
        while (portEnum.hasMoreElements()) {
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            if (listaPuertos == null) {
                listaPuertos = FXCollections.observableArrayList(currPortId.getName());
            } else {
                listaPuertos.add(currPortId.getName());
            }
        }
        comboBox.setItems(listaPuertos);
    }
}
